//
//  ViewController.m
//  PaySDKDemo
//
//  Created by LZ on 2018/7/25.
//  Copyright © 2018年 JLPAY. All rights reserved.
//

#import "TradeVC.h"
#import <JLSDK/JLSDK.h>
#import <AdSupport/AdSupport.h>
#import "JLDataConvert.h"
#import "WYDEncrypt.h"
#import "PaySDKConfig.h"
#import "JLSingleton.h"
#import "CocoaSecurity.h"
#import "JLServerTool.h"
#import "Base64.h"
#import "RSA.h"

static NSString *tradeAmount = @"2800";
static NSString *tradeFee    = @"500";
static NSString *cashType    = @"1";
static NSString *d0Fee       = @"300";

@interface TradeVC ()

@property (weak, nonatomic) IBOutlet UITextView *resultTxv;

@property (strong, nonatomic) JLDeviceKeyModel *keyModel;

@property (strong, nonatomic) NSString *pinEnKey;
@property (strong, nonatomic) NSString *tdEnKey;
@property (strong, nonatomic) NSString *macEnKey;

@end

@implementation TradeVC

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    
    [JLSDK setDebugMode:YES];
    [JLSDK sdkRequestLocationWithSuccess:^(CLLocation *loction) {
        
    } failure:^(NSError *error) {
        
    }];

}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark -
- (void)showResultMsg:(NSString *)msg{
    
    dispatch_async(dispatch_get_main_queue(), ^{
        self.resultTxv.text = msg;
    });
}

//登录
- (IBAction)loginClicked:(id)sender {
    
    NSString *phone_no = @"15673144162";
    NSString *password = @"123456";
    
    NSMutableDictionary *param = [NSMutableDictionary dictionary];
    param[@"phone_no"]   = phone_no;
    param[@"password"]  = [CocoaSecurity md5:password].hexLower;
    
    [param addEntriesFromDictionary:[JLServerTool baseParamWithType:@"022"]];
    NSString *jsonString = [JLServerTool jsonStrByJsonObj:param];
    
    [self showResultMsg:@"开始登录请求"];
    [JLSDK encryptRequestWithType:@"022"
                             json:jsonString
                          success:^(id data) {
                              
                              if(data){
                                  
                                  NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data
                                                                                       options:NSJSONReadingAllowFragments
                                                                                         error:nil];
                                  
                                  NSString *sessionId = dict[@"session_id"];
                                  if (sessionId.length > 0) {
                                      [JLSingleton share].sessionId = sessionId;
                                      
                                      NSLog(@"登录成功");
                                      [self showResultMsg:@"登录成功"];
                                      return;
                                  }
                                  
                                  NSString *reponseStr = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
                                  
                                  [self showResultMsg:[NSString stringWithFormat:@"登录数据%@",reponseStr]];
                                  return;
                              }
                              
                              
                              [self showResultMsg:@"登录数据异常"];
                              
                          } failure:^(NSError *error) {
                              NSLog(@"error:%@",error);
                              
                              [self showResultMsg:[NSString stringWithFormat:@"登录失败：%@",error.localizedDescription]];
                          }];
    
    
}

- (IBAction)createOrderClicked:(id)sender {
    
    NSString *money    = @"280";
    NSString *merch_no = @"84944035813A00H";
    NSString *term_no  = @"60004474";
    
    NSMutableDictionary *param = [NSMutableDictionary dictionary];
    param[@"merch_no"]   = merch_no;
    param[@"term_no"]    = term_no;
    param[@"amount"]     = tradeAmount;
    param[@"trans_fee"]  = tradeFee;
    param[@"d0_fee"]     = d0Fee;
    param[@"d0_flag"]    = cashType;
    
    [param addEntriesFromDictionary:[JLServerTool baseParamWithType:@"035"]];
    
    [self showResultMsg:@"开始创建订单请求"];
    NSString *jsonString = [JLServerTool jsonStrByJsonObj:param];
    [JLSDK encryptRequestWithType:@"035"
                             json:jsonString
                          success:^(id data) {
                              
                              if (data) {
                                  
                                  NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data
                                                                                       options:NSJSONReadingAllowFragments
                                                                                         error:nil];
                                  
                                  NSString *ret_code = dict[@"ret_code"];
                                  if ([ret_code isEqualToString:@"00"]) {
                                      NSString *orderId = dict[@"order_id"];
                                      [JLSingleton share].payMoney = money;
                                      [JLSingleton share].orderId  = orderId;
                                      [self showResultMsg:[NSString stringWithFormat:@"创建订单成功:%@",orderId]];
                                      
                                  }
                                  else{
                                      NSString *ret_msg = dict[@"ret_msg"];
                                      [self showResultMsg:[NSString stringWithFormat:@"创建订单失败:%@",ret_msg]];
                                  }
                                  
                                  NSLog(@"create order:%@",dict);
                              }
                              
                          } failure:^(NSError *error) {
                              NSLog(@"error:%@",error);
                              [self showResultMsg:@"创建订单失败"];
                          }];
}

#pragma mark - SDK注册
- (IBAction)sdkRegiterClicked{
    
    NSString *appId      = @"TEST_ANDROID";
    NSString *deviceNo   = @"N5IosTest01";
    NSString *sessionId  = [JLSingleton share].sessionId;
    //NSString *simCardNo  = @"";
    //NSString *apMac      = @"";
    NSString *appType    = @"MPOS";
    
    /*
    NSString *signMethod = @"02";
    
    NSString *signString = [NSString stringWithFormat:@"%@%@%@%@%@",deviceNo,simCardNo,apMac,appType,signMethod];
    //NSString *sha256Str  = [CocoaSecurity sha256:signString].hexLower;
    NSData *sha256Data  = [CocoaSecurity sha256:signString].data;
    
    NSString *priKey = @"MIIEvAIBADANBgkqhkiG9w0BAQEFAASCBKYwggSiAgEAAoIBAQCBUxiEWR7ouMHqQHsz08lyyP1m0cx64O8dQrSCaSqwqIiX2RyEiJeUhj80/c7braKV+KdEe6kMcmN+MlNOBpttJWEtizswZdDzIxR2rEVgVvZcwS1LBLYEXYY5p0fS70GXdijHt7e6gYO7sxjZm72BWp+xwmAaHATahIVKO+KXefzaqxz0OXgio59N9YxzNBI5adnCjfPt47mvvbFWm9eQfif2WmdzBBWq0liwLLyXnNx7N1lHwp3852UENbUFinN35+JHbE55GkkfBPPNEMIXgZyuACu6u/XD1tlHqmYvCUgYrNQL7u1Go6dqYDLlPbmIMsHdjVXy0jAx/rI0GNvzAgMBAAECggEAS1U8UtwXRTlavDoTin00O8kY02wi0PF2WHUi8VSRqZaC+vFdy1ZF9h69cwDmHtFmhDX0OdBPCREZI8ns/OacY1gC46TXNboZnYgxw29Wemgt2pos6CY2YRSZu7vV+umkK7aIys4aGGqZch1BvIEcQt2naMTxdkQcD65idnur4tA0rUB4PoeicY2ObsaFWFJaLFyw9LblKB/HlUPuPiUnaC2mw+4fWBpXuCwTD+q4sEd9ol1ohenkwvCPQfbENe6ClY3fKxztMuYfA6fwxI3T9lB5xeUDnEseCjIBTYDtIFvOHyuJS6FG1D3hRWK6G8/7kGjd8D0+Hdc8yY5WF2+IAQKBgQDcmlkfHz4GPqX6hzetm7VUCi+D/oi6aqXZ4UhNZTfTRnmZlNBrhlfYgUweZumHi/gjcD0T6TrYM21S0KD6L35HVTEh+d1QjmakF3G0CcC9U/uaNmdQiObxLjBnVQanYe5G6ZBNVNSh6NGLsRaLesExxBtAuEJ1McLRfwmvV+osIQKBgQCWE1SHmi/MD9+aElmGOdSq4WUOMTEKhm1oJDcjH9NZY9dkojQgypibBrxxPzEf1cgJO0rhx421m2mj/sCtqUnO+nnieBKVhbeaBSsJ0XwPCTvesi/cQkGizjFrTIksOyCzibV399Ylq3gNig1b5E2YEmK6RYM3sa5p2ibMGijlkwKBgFhJ+cMn6NXs+tayiUkVGVRCI1QraaNaDXiO3jYDfX00JnSeB3ARO1UuIj3EqFAUZ8IfKIKwhFmE84sCbnrSyTJZWSmk67tS0qd3ro0EnjvnwbmtblngALWj68FfWSNiYU/GKHearOMD3+GNhV1bSrjVKKcVV5u5x6O6uTCQ+eqhAoGACsDn1a+erSiWBRw7ffq22me8LgAoW3C2djfiG4o0Qrt8u6FDyvW5aaJZ7mNwya8v3jl5bCQ4a0LvluiyNb9jookgIrIn4r7qIQctxk5UbV9kAtkRxN6ahWfw8pdRXPH/rd24OxhvJ9PZjl7OBj+dr7/hgydn952rubn//bACLjECgYB5ddscmTPcj2ulOr2wIEoiL+MSr28l48NzcNbaX76bz5HCHFKREK4oS5eimllFuZqMuHSDVMpXZvPVk31800f/M2N+FWZytf7yqMmOjugv4T73MwFlbvHYs9p6luN6wrAnTuEP5mIGXFP+CmfRKp2lzUlRa+iWasGjjrtB55CXgQ==";

    NSLog(@"%ld",priKey.length);
    
    NSData *data = [RSA encryptData:sha256Data privateKey:priKey];
    NSString *signData = [data base64EncodedString];
    */
     
    if (appId.length < 1 || deviceNo.length < 1 || sessionId.length < 1 || appType.length < 1) {
        
        [self showResultMsg:@"上传数据不能为空"];
        return;
    }
    
    JLSDKInitModel *model = [[JLSDKInitModel alloc] init];
    model.app_id = appId;
    model.term_sn = deviceNo;
    model.session_id = sessionId;
    //model.simCardNo  = simCardNo;
    //model.apMac      = apMac;
    model.appType    = appType;
    //model.signMethod = @"02";
    //model.signData   = signData;
    
    
    [self showResultMsg:@"正在请求..."];
    [JLSDK registerWithModel:model
                      succes:^(JLDeviceKeyModel *data) {
                          
                          NSMutableString *string = [[NSMutableString alloc] init];
                          [string appendFormat:@"返回结果： Mac key:%@,mac_key_check_value:%@,pin_key:%@,pin_key_check_value:%@,td_key:%@,td_key_check_value:%@",data.mac_key,data.mac_key_check_value,data.pin_key,data.pin_key_check_value,data.td_key,data.td_key_check_value];
                          
                          self.pinEnKey = nil;
                          self.tdEnKey  = nil;
                          self.macEnKey = nil;
                          
                          self.keyModel = data;
                          [self showResultMsg:string];
                          
                      } failure:^(NSError *error) {
                          
                          NSString *string = [NSString stringWithFormat:@"错误：%@",error.localizedDescription];
                          [self showResultMsg:string];
                      }];
    
}


- (IBAction)sdkTransClicked{
    
    __weak typeof(self)weakSelf = self;
    
    if (!self.pinEnKey) {
        
        [self eMacWithMacKey:self.keyModel.pin_key
                       block:^(NSString *mak, NSString *macKeyCheckValue) {
                           //NSLog(@"mak:%@,%@",mak,macKeyCheckValue);
                           
                           NSString *serverMac = weakSelf.keyModel.pin_key_check_value;
                           if ([[macKeyCheckValue substringToIndex:8] isEqualToString:serverMac]) {
                               NSLog(@"pin key 明文校验通过");
                               
                               weakSelf.pinEnKey = mak;
                           }
                           else{
                               NSLog(@"pin key 明文校验未通过");
                               [self showResultMsg:@"pin key 明文校验未通过"];
                           }
                       }];
    }
    
    if (!self.tdEnKey) {
        [self eMacWithMacKey:self.keyModel.td_key
                       block:^(NSString *mak, NSString *macKeyCheckValue) {
                           //NSLog(@"mak:%@,%@",mak,macKeyCheckValue);
                           
                           NSString *serverMac = weakSelf.keyModel.td_key_check_value;
                           if ([[macKeyCheckValue substringToIndex:8] isEqualToString:serverMac]) {
                               NSLog(@"td key 明文校验通过");
                               
                               weakSelf.tdEnKey = mak;
                           }
                           else{
                               NSLog(@"td key 明文校验未通过");
                               [self showResultMsg:@"td key 明文校验未通过"];
                           }
                       }];
    }
    
    if (self.tdEnKey.length < 1 || self.pinEnKey.length < 1) {
        return;
    }

    NSString *cardno = @"6222024000027530241";
    NSString *pin   = @"123456";
    
    NSString *xorPin = [NSString stringWithFormat:@"%02d",(int)pin.length];
    xorPin = [xorPin stringByAppendingString:pin];
    int dis = (int)(16-xorPin.length);
    for (int i = 0;i < dis;i++) {
        xorPin = [xorPin stringByAppendingString:@"F"];
    }

    NSString *pan = [cardno substringWithRange:NSMakeRange(cardno.length-13, 12)];
    pan = [NSString stringWithFormat:@"%0*d%@",16-(int)pan.length,0,pan];
    
    NSData *pinData     = [JLDataConvert convertHexStrToData:xorPin];
    NSString *pinHexStr = [JLDataConvert convertDataToHexStr:pinData];
    
    NSData *panData     = [JLDataConvert convertHexStrToData:pan];
    NSString *panHexStr = [JLDataConvert convertDataToHexStr:panData];
    
    NSString *xorResult = [TradeVC xorWithString:pinHexStr string2:panHexStr];
    
    
    NSString *enPin = [WYDEncrypt threeDESEncrypt:xorResult withKey:self.pinEnKey];
    
    
    NSString *track2 = @"6222024000027530241=49121205619991282";
    if (track2.length % 2 != 0) {
        track2 = [track2 stringByAppendingString:@"0"];
    }
    
    NSInteger len        = track2.length;
    NSString *sub        = [track2 substringWithRange:NSMakeRange(len-18, 16)];
    NSData *track2Data   = [JLDataConvert convertHexStrToData:sub];
    NSString *track2Str  = [JLDataConvert convertDataToHexStr:track2Data];
    
    NSString *enTrack2   = [WYDEncrypt threeDESEncrypt:track2Str withKey:self.tdEnKey];
    
    track2 = [track2 stringByReplacingOccurrencesOfString:sub withString:enTrack2];
    
    NSString *track3 = @"996222024000027530241=156156000000000000000356199921600004912000000000000000000000=000000000000=00000000";
    if (track3.length-2 < 16) {
        track3 = [track3 stringByAppendingFormat:@"%*@",(int)(16-(track3.length - 2)),@"F"];
    }
    
    NSInteger len2 = track3.length;
    NSString *subTrack3   = [track3 substringWithRange:NSMakeRange(len2-18, 16)];
    NSString *temSubTrack3 = [subTrack3 stringByReplacingOccurrencesOfString:@"=" withString:@"D"];
    NSData *track3Data     = [JLDataConvert convertHexStrToData:temSubTrack3];
    NSString *track3Str    = [JLDataConvert convertDataToHexStr:track3Data];

    NSString *enTrack3  = [WYDEncrypt threeDESEncrypt:track3Str withKey:self.tdEnKey];
    
    track3 = [NSString stringWithFormat:@"%@%@%@",[track3 substringToIndex:len2-18],enTrack3,[track3 substringFromIndex:len2-2]];
    
    JLTradeData *data = [[JLTradeData alloc] init];
    data.amount    = tradeAmount;
    data.cardModel = JLCardModelMagneticCard;
    data.card_no   = cardno;
    data.track2    = track2; //@"6222024000027530241de795a210cd261ae22";
    data.track3    = track3;
    data.pin       = enPin;
    
    //app自定义数据
    //订单
    NSString *orderId       = [JLSingleton share].orderId;
    //交易手续费，分为单位
    NSString *fee           = tradeFee;
    //商户非标标志：0：标准商户，1：非标商户
    NSString *standard_flag = @"1";
    //d0方式 1:D0提现，0或者其他标示 非D0提现
    NSString *d0flag        = cashType;
    //d0提现手续费，分为单位
    NSString *d0FeeStr      = d0Fee;
    
    //APP自定义数据
    NSMutableArray *defineArray = [NSMutableArray array];
    if (orderId) {
        NSString *string = [NSString stringWithFormat:@"order_id=%@",orderId];
        [defineArray addObject:string];
    }
    if(fee){
        NSString *string = [NSString stringWithFormat:@"fee=%@",fee];
        [defineArray addObject:string];
    }
    if(d0flag){
        NSString *string = [NSString stringWithFormat:@"D0_flag=%@",d0flag];
        [defineArray addObject:string];
    }
    if (d0FeeStr) {
        NSString *string = [NSString stringWithFormat:@"D0_fee=%@",d0FeeStr];
        [defineArray addObject:string];
    }
    
    if(standard_flag){
        NSString *string = [NSString stringWithFormat:@"standard_flag=%@",standard_flag];
        [defineArray addObject:string];
    }
    NSString *app_define_data = [defineArray componentsJoinedByString:@"&"];
    data.app_define_data      = app_define_data;
    
    [self showResultMsg:@"正在请求..."];
    
    [JLSDK sdkTransWithParam:data
                    macBlock:^(NSString *xorStr, CallBack block) {
                        
                        [self campareMacValueWithXorStr:xorStr block:block];
                        
                    } success:^(JLPayTradeInfo *data) {
                        
                        [self showResultMsg:@"交易成功"];
                        
                    } failure:^(JLFailureModel *faiureModel) {
                        
                        if (faiureModel.type == -10) {
                            NSString *string = [NSString stringWithFormat:@"系统返回错误Code：%@,错误：%@",faiureModel.retCode,faiureModel.msg];
                            
                            [self showResultMsg:string];
                        }
                        else{
                            NSString *string = [NSString stringWithFormat:@"错误：%@",faiureModel.msg];
                            [self showResultMsg:string];
                        }
                    }];

}

- (IBAction)sdkEleClicked{
    
    [JLSDK sdkElesignWithOrderId:@"123"
                         signImg:[UIImage imageNamed:@"123"]
                         success:^(id data) {
                             
                             NSString *string = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
                             [self showResultMsg:string];
                             
                         } failure:^(JLFailureModel *faiureModel) {
                             
                        
                             
                             if (faiureModel.type == -10) {
                                 
                                 NSString *string = [NSString stringWithFormat:@"系统返回错误Code：%@,错误：%@",faiureModel.retCode,faiureModel.msg];
                                 
                                 [self showResultMsg:string];
                             }
                             else{
                                 NSString *string = [NSString stringWithFormat:@"错误：%@",faiureModel.msg];
                                 [self showResultMsg:string];
                             }
                         }];

}

#pragma mark -
- (void)campareMacValueWithXorStr:(NSString *)xorStr block:(CallBack)black{
    
    
    if (!self.macEnKey) {
        __weak typeof(self)weakSelf = self;
        [self eMacWithMacKey:self.keyModel.mac_key
                       block:^(NSString *mak, NSString *macKeyCheckValue) {
                           //NSLog(@"mak:%@,%@",mak,macKeyCheckValue);
                           
                           NSString *serverMac = weakSelf.keyModel.mac_key_check_value;
                           if ([[macKeyCheckValue substringToIndex:8] isEqualToString:serverMac]) {
                               NSLog(@"mac key 明文校验通过");
                               
                               weakSelf.macEnKey = mak;
                           }
                           else{
                               //NSLog(@"mac key 明文校验未通过");
                               [self showResultMsg:@"mac key 明文校验未通过"];
                           }
                           
                           NSString *mac = [weakSelf aesWithEMac:mak xor:xorStr];
                           if (black) {
                               black(mac);
                           }
                       }];
    }
    else{
        NSString *mac = [self aesWithEMac:self.macEnKey xor:xorStr];
        if (black) {
            black(mac);
        }
    }
}

- (NSString *)aesWithEMac:(NSString *)eMac xor:(NSString *)xor{
    
    NSString *asHex = [JLDataConvert hexConvertFromAscii:[xor uppercaseString]];
    
    NSData *data1    = [JLDataConvert convertHexStrToData:asHex];
    NSData *tmpData1 = [data1 subdataWithRange:NSMakeRange(0, 8)];
    NSData *tmpData2 = [data1 subdataWithRange:NSMakeRange(8, 8)];
    
    NSString *tmpStr1 = [JLDataConvert convertDataToHexStr:tmpData1];

    NSString *value   = [WYDEncrypt threeDESEncrypt:tmpStr1 withKey:eMac];
    NSString *lastXor = [JLDataConvert convertDataToHexStr:tmpData2];
    
    //NSString *value = [CocoaSecurity aesEncrypt:subXor key:eMac].hex;
    
    //加密字符和后8个字符异或
    NSString *result1 = [TradeVC xorWithString:value string2:lastXor];
    //在加密
    NSString *value2 = [WYDEncrypt threeDESEncrypt:result1 withKey:eMac];
    //16位的hex
    //NSData *data2 = [value2 dataUsingEncoding:NSUTF8StringEncoding];
    //NSString *result2 = [JLDataConvert convertDataToHexStr:data2];
    NSString *asStr = [JLDataConvert hexConvertFromAscii:[value2 uppercaseString]];
    
    NSString *subValue2 = [asStr substringToIndex:16];
    
    NSString *mac  = [JLDataConvert ASCIIConvertFromBCD:subValue2];
    

    return mac;
    
}


#pragma mark -
//eMac
- (void)eMacWithMacKey:(NSString *)macKey block:(void(^)(NSString *mak, NSString *macKeyCheckValue))block {
    
    //mackey 得到mackey明文 用于mac计算加密
    NSString *mak = [self getDesMakey:macKey];
    //macKey校验密文
    NSString *macKeyCheckValue = [self getMacKeyCheckValue:mak];
    
    //回调
    if (block) {
        block(mak, macKeyCheckValue);
    }
}

//解密macKey密文
- (NSString *)getDesMakey:(NSString *)macKey{
    
    //NSLog(@"%d",(int)macKey.length);
    
    NSString *mak  = [WYDEncrypt threeDESDecrypt:macKey withKey:@"F78CE5D6434C1C808591B9F8B9319ECB"];

    return mak;
}


//计算macKey校验密文 macKey明文
- (NSString *)getMacKeyCheckValue:(NSString *)mak{

    NSString *string     = @"0000000000000000";
    NSString *checkValue = [WYDEncrypt threeDESEncrypt:string withKey:mak];

    return checkValue;
}



#pragma mark - 异或处理
+ (NSString *)xorWithString:(NSString *)str1 string2:(NSString *)str2{
    
    NSData *data1 = [JLDataConvert convertHexStrToData:str1];
    NSData *data2 = [JLDataConvert convertHexStrToData:str2];;
    
    NSData *xorData = [self xorWithData1:data1 data2:data2];
    NSString *value = [JLDataConvert convertDataToHexStr:xorData];
    return value;
}

+ (NSData *)xorWithData1:(NSData *)data1 data2:(NSData *)data2{
    
    NSMutableData *encryptData = [NSMutableData data];
    
    const Byte *tmpData1Char = [data1 bytes];
    const Byte *tmpData2Char = [data2 bytes];
    
    for (int x = 0; x< data1.length; x ++) {
        Byte byte = tmpData1Char[x]^tmpData2Char[x];
        [encryptData appendBytes:&byte length:1];
    }
    
    return encryptData.copy;
}

#pragma mark - UITextFieldDeleagte
- (BOOL)textFieldShouldReturn:(UITextField *)textField{
    [textField resignFirstResponder];
    return YES;
}

#pragma mark - 
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    [self.view endEditing:YES];
}


@end
